package com.shqyang.yexplorer.util

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Environment
import android.provider.Settings
import androidx.core.app.ActivityCompat
import androidx.core.net.toUri

/**
 * Created by Swsbty on 2021/03/14
 */
const val REQUEST_PERMISSION_CODE = 9527

fun Activity.checkFilePermissions(): Boolean {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) != 0) {
            ActivityCompat.requestPermissions(
                this, arrayOf(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                ), REQUEST_PERMISSION_CODE
            )
            return false
        } else {
            return true
        }
    } else {
        return Environment.isExternalStorageManager()
    }
}

fun Activity.hasReadFilePermission(): Boolean {
    return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
        ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.READ_EXTERNAL_STORAGE
        ) == 0
    } else {
        Environment.isExternalStorageManager()
    }
}

fun Context.checkAndGrantPermissions(): Boolean {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        if (!Environment.isExternalStorageManager()) {
            startActivity(Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION).apply {
                data = "package:$packageName".toUri()
            })
            return false
        } else {
            return true
        }
    } else {
        return true
    }
}